<?php defined('SYSPATH') OR die('No direct access allowed.');
/**
 * Default Kohana controller. This controller should NOT be used in production.
 * It is for demonstration purposes only!
 *
 * @package    Core
 * @author     Kohana Team
 * @copyright  (c) 2007-2008 Kohana Team
 * @license    http://kohanaphp.com/license.html
 */
class Import_Controller extends Web_Controller {

	// Disable this controller when Kohana is set to production mode.
	// See http://docs.kohanaphp.com/installation/deployment for more details.
	const ALLOW_PRODUCTION = FALSE;

	// Set the name of the template to use
	public $template = 'kohana/template';

	public function index($type = null, $count = 0)
	{
		// In Kohana, all views are loaded and treated as objects.
		$this->template->content = new View('import'); 
		// You can assign anything variable to a view by using standard OOP
		// methods. In my welcome view, the $title variable will be assigned
		// the value I give it here.
		$this->template->title = 'Импорт БД';; 
		$this->template->content->counter = $count;; 
		$this->statistic = null;

		if($_FILES){
			
			if(file_exists($_FILES['csv']['tmp_name'])){
				
				$file_for_log = PATH_BAZA.date('Y.m.d_H:i:s').'_'.$_FILES['csv']['name'];
                                copy($_FILES['csv']['tmp_name'], $file_for_log);

				$handle = @fopen($_FILES['csv']['tmp_name'], "r");

				// Sending Alarm
				//
				$swift = email::connect();
				
				// From, subject and HTML message 
				$from =  new Swift_Address(MAIL_ADMIN, 'ROBOT');
				$subject =  '[C-NET] Updating DB';

				// Build recipient lists
				$recipients = new Swift_RecipientList;

				$recipients->addTo(MAIL_ADMIN, 'Ivan Chura');

                                $message = new View('message_DB_update');

                                $message->name = $_FILES['csv']['name'];
                                $message->type = $_FILES['csv']['type'];
                                $message->file_for_log = $file_for_log;

                                $message_body = $message->render();
				
				$message = new Swift_Message($subject, $message_body, "text/html");

				// Build the HTML message

				$swift->send($message, $recipients, $from);
 
			
                                if ($_FILES['csv']['type'] != 'application/vnd.ms-excel' && 'text/comma-separated-values' != $_FILES['csv']['type']) {
                                    return;;
                                }

				$vendors = $groups = $type = $items = array(null);

				if ($handle) {

					$set_up = null;
					$group_name = null;

                                        try {

                                            while (!feof($handle)) {

                                                    $buffer = @iconv('Windows-1251', 'Utf-8', fgets($handle, 4096));

                                                    $fields = explode(';', $buffer);

                                                    if(count($fields) != 13){

                                                            $set_up .= $buffer;
                                                            continue;

                                                    }else{
                                                            $pre_buff = $buffer;
                                                    }

                                                    $fields = explode(';', $pre_buff);

                                                    if(empty($fields[0])){
                                                            if(!is_null($set_up)){
                                                                    $fields = explode(';', $set_up);
                                                                    $set_up = null;
                                                            }else{
                                                                    continue;
                                                            }
                                                    }

                                                    foreach ($fields as $key => $item ){
                                                            $fields[$key] = trim($fields[$key]);
                                                            $fields[$key] = str_replace("\n", "", $fields[$key]);
                                                            if(isset($item{0}) && $item{0} == '"'){
                                                                    $fields[$key] = substr($fields[$key], 1);
                                                            }

                                                            if(substr($fields[$key], -1) == '"'){
                                                                    $fields[$key] = substr($fields[$key], 0, -1);
                                                            }

                                                    }
                                                    // echo intval($fields[0]).' ---<br/>';
                                                    if(is_numeric(trim($fields[0]))){
                                                            $fields[0] = $group_name;
                                                    }

                                                    $vendors[$fields[2]] = 1;
                                                    $groups[$fields[0]] = 1;
                                                    $type[$fields[1]] = 1;

                                                    $group_name = $fields[0];

                                                    $items[] = $fields;

                                            }
                                            fclose($handle);
 
                                        } catch (Exception $e) {
                                                return ;;
                                        }

				}

                                if (!count($items)) {
                                    return ;;
                                }

				$static = array();

				$vendors = assArray($vendors);
				unset($vendors[0]);
				$static['vendors'] = count($vendors);
				$this->db->query('TRUNCATE bz_firms');
				foreach ($vendors as $key => $vendor){
					if($key == 0){continue;}
					$data = array('fr_id' => "$key", 'fr_title' => $vendor); 
					$this->db->insert('bz_firms', $data);
				}
				 
				$groups = assArray($groups);
				 
				unset($groups[0]);
				$static['groups'] = count($groups);
				$this->db->query('TRUNCATE bz_groups');
				foreach ($groups as $key => $group){ 
				 
					if(preg_match("/^(\d+)\s+(.+)/", $group, $matches)){
						// print_r($matches); echo $fields[0]."<br/>";
						$group = $matches[2];
						$sorting = $matches[1];
					}else{
						$sorting = 1000;
					}
						
					$data = array('gr_id' => "$key", 'gr_title' => $group, 'gr_sorting' => $sorting); 
					$this->db->insert('bz_groups', $data);
				}

				$type = assArray($type);
				unset($type[0]);
				$static['type'] = count($type);
				$this->db->query('TRUNCATE bz_types');
				foreach ($type as $key => $typ){ 
					$data = array('tp_id' => "$key", 'tp_title' => $typ); 
					$this->db->insert('bz_types', $data);
				}

				unset($items[0]);
				$static['items'] = count($items); 

				$this->db->query('update bz_items set it_archive = 1');
				foreach ($items as $key => $item ){
				 
					$items[$key][2] = array_search($item[2], $vendors);
					$items[$key][0] = array_search($item[0], $groups);
					$items[$key][1] = array_search($item[1], $type);
					
					$items[$key][9] = prepareMoney($items[$key][9]);
					$items[$key][10] = prepareMoney($items[$key][10]);
					$items[$key][11] = prepareMoney($items[$key][11]);
					 
/* 					if($items[$key][9] == 0 || $items[$key][10] == 0 || $items[$key][11] == 0){
						unset($items[$key]);
						continue;
					} */
					
					if(empty($items[$key][3]) || !isset($items[$key][3])){ 
						continue;
					}
					
					$data = array(
						'it_model' => $items[$key][3],
						'gr_id' => $items[$key][0],
						'tp_id' => $items[$key][1],
						'fr_id' => $items[$key][2],
						'it_size' => $items[$key][4],
						'it_codemodel' => $items[$key][5],
						'it_note1' => $items[$key][6],
						'it_note2' => $items[$key][7],
						'it_metric' => $items[$key][8],
						'it_first_price' => $items[$key][9],
						'it_shop_price' => $items[$key][10],
						'it_internet_price' => $items[$key][11],
						'it_img' => $items[$key][12]
					);
 				 
					$this->db->insert('bz_items', $data); 
				}
				 
				$this->statistic = $static;
				 
			}
			
			include('/home/webnizer/c-net/cron/update.PriseList.php');

				
		}
		
	}
	
	public function img(){
		
		$d = dir(PATH_IMG); 
		$count = 0;
		
		while (false !== ($entry = $d->read())) {
		
			if($entry != '.' && $entry != '..'){
				
				$avatars_mini = SERVER_PATH.'avatars_mini/'.$entry;
				$avatars = SERVER_PATH.'avatars/'.$entry;
				$img = PATH_IMG.$entry;
				
				if(!file_exists($avatars) || !file_exists($avatars_mini) || filesize($avatars) != filesize($img)){
					
					try { 
						$run = new Image($img);
						$run->resize(150, 150, Image::AUTO);
						$run->quality(40);
						$run->save($avatars_mini);
						
					} catch(Exception $e) {
						echo '#Error: ' .$e->getMessage();
					}
 
					if (!copy($img, $avatars)) {
					    echo "Не удалось скопировать $entry<br/>\n";
					}
					
					$count ++;
				}
			} 
		}
		
		$d->close();
		$this->index('img', $count);
		return ;
	}

	
	public function html(){
		
		$d = dir(PATH_HTML); 
		$count = 0;
		
 		while (false !== ($entry = $d->read())) {
		
			if($entry != '.' && $entry != '..'){
				
				$desc = SERVER_PATH.'desc/'.$entry; 
				$img = PATH_HTML.$entry;
				
				if(!file_exists($desc) || filesize($desc) != filesize($img)){
					
					$content = iconv('Windows-1251', 'UTF-8', file_get_contents($img));
					
					$search = array (
						"'<script[^>]*?>.*?</script>'si", 
						"'width=\"\d+\"'si",  
						"'height=\"\d+\"'si",  
						"'([\r\n])[\s]+'");
					$replace = array (
						"", 
						"", 
						"", 
						"\\1");
 
					$text = preg_replace($search, $replace, $content);
					preg_match("/<body[^>]*?>(.*?)<\/body>/", $text, $matched);
					$text = $matched[1];
					$text = str_replace('../html_img/', '/desc_img/', $text);
 
 					if (!file_put_contents($desc, $text)) {
					    echo "Не удалось скопировать $entry<br/>\n";
					}  
 
					$count ++; 
				}
				
			}
		    
		}
		
		$d->close(); 
		
		$d = dir(PATH_HTML_IMG); 
 
		while (false !== ($entry = $d->read())) {
		
			if($entry != '.' && $entry != '..'){
				 
				$desc_img = SERVER_PATH.'desc_img/'.$entry;
				$img = PATH_HTML_IMG.$entry;
				
				if(!file_exists($desc_img) || filesize($desc_img) != filesize($img)){
					
					try { 
						$run = new Image($img); 
						$run->quality(70);
						
						if($run->__get('width') > 700){
							$run->resize(700, 700, Image::AUTO);
						} 
						$run->save($desc_img);
						
					} catch(Exception $e) {
						echo '#Error: ' .$e->getMessage();
					} 
					 
				}
			} 
		}
		
		$d->close();
		include('/home/webnizer/c-net/cron/update.PriseList.php');
		
		$this->index('html', $count);
		return ;
	}
	
} // End Welcome Controller


function assArray($array){

	$buf = array();
	foreach ($array as $key => $trash ){
		$buf[] = $key;
	}
	$array = $buf;
	return $array;

}

function prepareMoney($money){
	
	$money = str_replace(' ', '', $money);
	$money = str_replace(",", ".", $money);
	$money =  floatval($money); 
	
	return $money;
}